package com.xatz.scanner

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.recyclerview.widget.RecyclerView
import com.xatz.scanner.bean.ResponseBean
import com.xatz.scanner.databinding.ActivitySoldStockOutBinding
import com.xatz.scanner.databinding.ItemSoldStockOutBinding
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import wang.relish.widget.vehicleedittext.VehicleKeyboardHelper
import java.text.SimpleDateFormat
import java.util.*

/**
 * author: tdq
 * date: 2021/7/20
 * description: 已售出库
 */
class SoldStockOutActivity : AppCompatActivity(),
    ScannerManger.OnScannerResultListener, SoldStockOutAdapter.OnItemClickListener {

    private lateinit var mBinding: ActivitySoldStockOutBinding

    private val mCodes = mutableListOf<String>()

    private val adapter = SoldStockOutAdapter(mCodes)

    private val netProgressDialog by lazy { NetProgressDialog(this) }

    private val mService by lazy {
        ScannerRetrofitClient().getService(
            ScannerService::class.java,
            ScannerService.baseGoodsUrl9081
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivitySoldStockOutBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        VehicleKeyboardHelper.bind(mBinding.etCar)
        ScannerManger.init(this)
        ScannerManger.setOnScannerResultListener(this)

        var externalFileRootDir = getExternalFilesDir(null)
        do {
            externalFileRootDir = Objects.requireNonNull(externalFileRootDir)?.parentFile
        }while (Objects.requireNonNull(externalFileRootDir)?.absolutePath?.contains("/Android") == true)
        Timber.e(externalFileRootDir?.absolutePath)
        mBinding.tlLayout.setRightViewOnClick {
            val num = mBinding.etNum.text?.trim().toString()
            if (num.isEmpty()) {
                Toast.makeText(this, "请输入条形码号", Toast.LENGTH_SHORT).show()
                return@setRightViewOnClick
            }
            intent.putExtra("numText", num)
            setResult(RESULT_OK, intent)
            finish()
        }

        adapter.setOnItemClickListener(this)
        mBinding.rvCarInfo.adapter = adapter

        mBinding.btnSubmit.setOnClickListener {
            val carNum = mBinding.etCar.text?.trim().toString()
            if (carNum.isNullOrBlank()) {
                toast("请输入车牌号码！")
                return@setOnClickListener
            }
            if (mCodes.isEmpty()) {
                toast("请扫描或添加条码！")
                return@setOnClickListener
            }
            val userAccount = getSharedPreferences(
                Constant.configName,
                Context.MODE_PRIVATE
            ).getString(Constant.userAccount, "").toString()
            netProgressDialog.showDialog()
            val json = JSONObject()
            val codeArray = JSONArray()
            mCodes.forEach {
                Timber.e(it)
                codeArray.put(it)
            }
            json.put("operPerson", userAccount)
            json.put(
                "operTime",
                SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().time)
            )
            json.put("codes", codeArray)
            json.put("carNum", carNum)
            Timber.e(json.toString())
            val params = json.toString().toRequestBody("application/json".toMediaTypeOrNull())
            mService.soldStockOutReceipt(params).enqueue(object : Callback<ResponseBean> {
                override fun onResponse(
                    call: Call<ResponseBean>,
                    response: Response<ResponseBean>
                ) {
                    netProgressDialog.dismiss()
                    if (response.isSuccessful) {
                        if (response.body()?.code == "0") {
                            toast("提交成功！")
                            mBinding.etNum.text?.clear()
                            mCodes.clear()
                            adapter.notifyDataSetChanged()
                        } else {
                            toast(response.body()?.message ?: "访问失败")
                        }
                    } else {
                        toast("访问失败")
                    }
                }

                override fun onFailure(call: Call<ResponseBean>, t: Throwable) {
                    netProgressDialog.dismiss()
                    Timber.e(t)
                    toast(t.message ?: "访问失败")
                }
            })
        }

        mBinding.btnAdd.setOnClickListener {
            val code = mBinding.etNum.text?.trim().toString()
            if (code.isNullOrBlank()) {
                toast("请输入条形码！")
                return@setOnClickListener
            }
            if (mCodes.contains(code)) {
                runOnUiThread {
                    toast("请勿重复添加！")
                }
                return@setOnClickListener
            }
            mCodes.add(code)
            adapter.notifyDataSetChanged()
            mBinding.etNum.text?.clear()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ScannerManger.onClosed()
    }

    override fun onResume() {
        super.onResume()
        // The application is in foreground
        if (ScannerManger.emdkManager != null) {
            // Acquire the barcode manager resources
            ScannerManger.initBarcodeManager(this)
        }
    }

    override fun onPause() {
        super.onPause()
        // The application is in background
        // Release the barcode manager resources
        ScannerManger.deInitScanner()
        ScannerManger.deInitBarcodeManager()
    }

    override fun onScannerResult(data: String?, labelType: String) {
        data?.run {
            if (this.startsWith("SO")) {
                runOnUiThread {
                    Toast.makeText(this@SoldStockOutActivity, "请扫描件次编码！", Toast.LENGTH_SHORT).show()
                }
                return@run

            } else {
                // 二维码
                try {
                    if (this.startsWith("http://")) {
                        val strArray = this.split("ID=")
                        if (mCodes.contains(strArray[1])) {
                            runOnUiThread {
                                toast("请勿重复添加！")
                            }
                            return@run
                        }
                        mCodes.add(strArray[1])
                    } else {
                        if (mCodes.contains(data)) {
                            runOnUiThread {
                                toast("请勿重复添加！")
                            }
                            return@run
                        }
                        mCodes.add(data)
                    }
                    runOnUiThread {
                        adapter.notifyDataSetChanged()
                    }
                } catch (e: Exception) {
                    Timber.e(e)
                }

            }
        }
    }

    override fun onItemClick(position: Int) {
        val dialog =
            android.app.AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("确定删除此条编号吗？")
                .setPositiveButton("确定") { dialog, _ ->
                    dialog.dismiss()
                    mCodes.removeAt(position)
                    adapter.notifyDataSetChanged()
                }
                .setNegativeButton("取消") { dialog, _ ->
                    dialog.dismiss()
                }
        dialog.show()

    }
}


class SoldStockOutAdapter(private val codes: MutableList<String>) :
    RecyclerView.Adapter<SoldStockOutAdapter.SoldStockOutViewHolder>() {

    class SoldStockOutViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvCarNum: TextView? = null
        var tvPosition: TextView? = null
        var btnDelete: AppCompatButton? = null

        init {
            tvCarNum = itemView.findViewById(R.id.tvCarNum)
            tvPosition = itemView.findViewById(R.id.tvPosition)
            btnDelete = itemView.findViewById(R.id.btnDelete)
        }
    }

    private var onItemClickListener: OnItemClickListener? = null

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): SoldStockOutViewHolder {
        return SoldStockOutViewHolder(
            ItemSoldStockOutBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            ).root
        )
    }


    override fun getItemCount(): Int {
        return codes.size
    }

    override fun onBindViewHolder(
        holder: SoldStockOutViewHolder,
        position: Int
    ) {
        holder.tvCarNum?.text = codes[position]
        holder.tvPosition?.text = (position + 1).toString()
        holder.btnDelete?.setOnClickListener {
            onItemClickListener?.onItemClick(position)
        }
    }
}